package cn.zzf.algs.note.base.collection.v1;

import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;

/**
 * @author GaoFeng
 * @date 2019/11/28 9:24
 */
public class LinkedBag<T> implements Iterable<T> {

    /**
     * 首节点
     */
    private Node<T> last;

    /**
     * 背包数量
     */
    private int size;

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void add(T element) {
        Node<T> node = new Node<>(element, null);
        if (this.last == null) {
            this.last = node;
        } else {
            last.next = node;
            this.last = last.next;
        }
    }

    public void reserve(Node<T> first) {

        if (first == null) {
            return;
        }

        Node<T> node = null;
        Node<T> currentNode = first;

        while (currentNode != null) {

            if (node == null) {
                node = currentNode;
            } else {
                Node<T> newNode = new Node<>(currentNode.value, null);
                newNode.next = node;
                node = newNode;
            }

            currentNode = currentNode.next;

        }

        StdOut.println(node);


        // 原地改变first的引用
        first.value = node.value;
        first.next = node.next;

    }

    public Node<T> reserveV2(Node<T> node) {

        Node<T> first = node;


        if (first == null) {
            return null;
        }


        if (first.next == null) {
            return first;
        }

        Node<T> second = null;
        Node<T> reserve = null;

        while (first != null) {
             second = first.next;
             first.next = reserve;
             reserve = first;
             first = second;
        }

        StdOut.println(reserve);

        return reserve;

    }



    @Override
    public Iterator<T> iterator() {

        return new Iterator<T>() {

            private Node<T> currentNode = last;

            @Override
            public boolean hasNext() {
                return currentNode != null;
            }

            @Override
            public T next() {
                if (currentNode != null) {
                    T value = currentNode.value;
                    currentNode = currentNode.next;
                    return value;
                }

                return null;
            }
        };

    }


}


